package com.l024.easysecurity.modules.sys.shiro;

import com.l024.easysecurity.common.utils.Constant;
import com.l024.easysecurity.modules.sys.dao.SysMenuMapper;
import com.l024.easysecurity.modules.sys.dao.SysUserMapper;
import com.l024.easysecurity.modules.sys.entity.SysUser;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 *认证
 */
@Component
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private SysMenuMapper sysMenuMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取到用户信息
        SysUser user = (SysUser)principals.getPrimaryPrincipal();
        if (user!=null){
            Long userId = user.getUserId();
            List<String> permsList;
            if(userId == Constant.SUPER_ADMIN){
                //管理员获取所有权限
                permsList = sysMenuMapper.queryAdminAllPerms();

            }else{
                //根据用户id去查询权限
                permsList = sysUserMapper.queryAllPerms(userId);
            }
            //用户权限列表
            Set<String> permsSet = new HashSet<>();
            for(String perms : permsList){
                if(StringUtils.isBlank(perms)){
                    continue;
                }
                //逗号分割
                permsSet.addAll(Arrays.asList(perms.trim().split(",")));
            }
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            simpleAuthorizationInfo.setStringPermissions(permsSet);
            return simpleAuthorizationInfo;
        }
        return null;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken)authcToken;
        //查询用户信息
        SysUser user = sysUserMapper.findUserByUserName(token.getUsername());
        if(user==null){
            throw new UnknownAccountException("账号或密码不正确");
        }
        //账号锁定
        if(user.getStatus() == 0){
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());
        return info;
    }

    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        HashedCredentialsMatcher shaCredentialsMatcher = new HashedCredentialsMatcher();
        shaCredentialsMatcher.setHashAlgorithmName(ShiroUtils.hashAlgorithmName);
        shaCredentialsMatcher.setHashIterations(ShiroUtils.hashIterations);
        super.setCredentialsMatcher(shaCredentialsMatcher);
    }
}
